package com.thread;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class JUC_CompletableFuture {

    private static double TM(){
        delay();
        return 1.00;
    }
    private static double TB(){
        delay();
        return 2.00;
    }
    private static double JD(){
        delay();
        return 3.00;
    }

    private static void delay() {
        int time = new Random().nextInt(500);
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sleep time:"+time);
    }

    public static void main(String[] args) {
        long start,end;
        start = System.currentTimeMillis();
        CompletableFuture<Double> pTM = CompletableFuture.supplyAsync(() -> TM());
        CompletableFuture<Double> pTB = CompletableFuture.supplyAsync(() -> TB());
        CompletableFuture<Double> pJD = CompletableFuture.supplyAsync(() -> JD());

        CompletableFuture.allOf(pJD,pTB,pTM).join();

        CompletableFuture.supplyAsync(()->TM())
                .thenApply(String::valueOf)
                .thenApply(str -> "price "+str)
                .thenAccept(System.out::println);
        System.out.println(System.currentTimeMillis() - start)
        ;

    }
}
